<template>
	<view class="manual-entry">
		<!-- 顶部导航 -->
		<view class="bf">
			<view class="tabsStyl" :style="[style]">
				<tabs-swiper ref="tabSwiper" :bar-height="10" :duration="300" :bar-style="{}" :active-color="'#333'"
					:list="navList" :is-scroll="false" :font-size="30" :current="currentTab" :bold="true"
					:offset="[5, 20]" :bg-color="'#FFF'" :inactive-color="'#333'" :active-item-style="{}" :barWidth="40"
					:barHeight="10" :box-padding="[0, 0]"
					:background-bar="'linear-gradient(to right, rgb(254, 147, 103), rgb(254, 147, 103))'"
					@change="changeTab"></tabs-swiper>
			</view>
		</view>

		<!-- 手动录单内容 -->
		<view v-if="currentTab === 0" class="content-section">
			<view class="template-editor">
				<u-input v-model="editableTemplate" type="textarea" placeholder="点击编辑示例模板" :auto-height="true"
					:border="true" placeholder-style="color:#999;" />
			</view>

			<view class="action-btns">
				<button class="copy-btn" @click="copyTemplate">复制测试信息</button>
				<button class="paste-btn" @click="parseTemplate">粘贴并识别</button>
			</view>

			<view class="entry-form">
				<view class="form-item">
					<u-input v-model="formData.serial" placeholder="#输入流水号" />
				</view>
				<view class="form-item">
					<text class="label">手机号：</text>
					<u-input v-model="formData.phone" placeholder="输入手机号" type="number" />
				</view>
				<view class="form-item">
					<text class="label">姓名：</text>
					<u-input v-model="formData.name" placeholder="无姓名" />
				</view>
				<view class="form-item">
					<text class="label">地址：</text>
					<u-input v-model="formData.address" placeholder="输入地址" />
				</view>
				<view class="form-item">
					<text class="label">备注：</text>
					<u-input v-model="formData.remark" placeholder="输入备注" />
				</view>
			</view>

			<button class="submit-btn" @click="submitForm">确定</button>
		</view>

		<!-- 录单记录内容 -->
		<view v-if="currentTab === 1" class="record-section">
			<view class="filter-bar">
				<scroll-view class="ws-n sarr pt10 bf p03" scroll-x="true">
					<block v-for="(v,i) in timeFilters" :key="i">
						<view @click="changeTimeFilter(i)" class="f-g-0 mr15 bs10 c6 dis-in sarri f28 t-c"
							:class="{wei:v.active}" style="width: auto;min-width: 118rpx;padding: 0 20rpx;"
							:style="{background:v.active?`rgba(254, 147, 103, 0.2)`:'',color:v.active?'#333':'#666'}">
							{{v.name}}
						</view>
					</block>
				</scroll-view>
			</view>

			<view class="record-list" style="padding: 0 40rpx 0 40rpx;">
				<view v-for="(item, index) in filteredRecords" :key="index" class="record-item">
					<!-- 单号字段不显示标题 -->
					<view class="record-field">
						<text class="value" style="color: red;font-weight: bold;">#{{ item.serial }}</text>
					</view>
					
					<view class="record-field">
						<view class="line"></view>
						<text class="label">姓名：</text>
						<text class="value">{{ item.name }}</text>
					</view>
					<view class="record-field">
						<view class="line"></view>
						<text class="label">手机号：</text>
						<text class="value">{{ item.phone }}</text>
					</view>
					<view class="record-field">
						<view class="line"></view>
						<text class="label">地址：</text>
						<text class="value">{{ item.address }}</text>
					</view>
					<view class="record-field">
						<view class="line"></view>
						<text class="label">备注：</text>
						<text class="value">{{ item.remark }}</text>
					</view>
					<view class="record-field">
						<view class="line"></view>
						<text class="label">时间：</text>
						<text class="value">{{ item.createTime }}</text>
					</view>
					<view class="record-field">
						<view class="line"></view>
						<text class="label">状态：</text>
						<text class="value">{{ item.status | statusText }}</text>
					</view>
				</view>
				<jzz bgcolor="transparent" imgn="zwhb" :nodata="filteredRecords.length === 0" />
			</view>
		</view>

		<u-calendar v-model="showCalendar" mode="range" :btnstyle="{ background: ' #FE9367' }" range-color=" #FE9367"
			range-bg-color="rgba(253,215,75,0.2)" active-bg-color='#FE9367' @change="changeDate" />
	</view>
</template>

<script>
	import TabsSwiper from '@/components/custom-tabs-page-linkge/u-tabs-swiper/custom-tabs-swiper.vue';
	import jzz from '@/components/common/jzz.vue';

	export default {
		components: {
			TabsSwiper,
			jzz
		},
		data() {
			return {
				// 录单记录数据（静态数据）
				records: [{
						serial: '20251010001',
						name: '用户姓名',
						phone: '13800138000',
						address: '长沙市雨花区复地6栋16070100号',
						remark: '紧急订单',
						createTime: '2025-03-17 11:30:00',
						status: 0
					},
					{
						serial: '20251010002',
						name: '李四',
						phone: '13912345678',
						address: '长沙市雨花区复地6栋16070500号',
						remark: '特殊包装要求',
						createTime: '2025-03-16 11:30:00',
						status: 0
					},
					{
						serial: '20251009001',
						name: '王五',
						phone: '13698765432',
						address: '长沙市雨花区复地6栋16070',
						remark: '到付订单',
						createTime: '2025-03-12 11:30:00',
						status: 0
					},
					{
						serial: '20251008001',
						name: '赵六',
						phone: '13511223344',
						address: '长沙市雨花区复地6栋16070',
						remark: '预约下午送达',
						createTime: '2025-03-01 11:30:00',
						status: 0
					}
				],
				// 导航相关
				navList: [{
						name: '手动录单',
						type: 0
					},
					{
						name: '录单记录',
						type: 1
					}
				],
				currentTab: 0,
				tabWidth: '100%',

				// 手动录单数据
				editableTemplate: "1名字 18000000000 地址信息 省注信息",
				formData: {
					serial: '',
					phone: '',
					name: '',
					address: '',
					remark: ''
				},

				// 记录相关
				timeFilters: [{
						name: '今天',
						active: true,
						days: 0
					},
					{
						name: '近7天',
						active: false,
						days: 7
					},
					{
						name: '近30天',
						active: false,
						days: 30
					},
					{
						name: '自定义',
						active: false,
						days: -1
					}
				],
				showCalendar: false,
				filterParams: {
					startTime: '',
					endTime: '',
					page: 1,
					size: 10
				},
				loading: false,
				noMore: false
			}
		},
		computed: {
			// 根据时间和状态过滤数据
			filteredRecords() {
			 return this.records.filter(record => {
				 // 过滤状态为已完成的记录
				 return record.status === 0 && this.filterByDate(record);
			 });
			}
		},
		filters: {
			statusText(val) {
				const statusMap = {
					0: '已完成'
				}
				return statusMap[val] || '未知状态'
			}
		},
		methods: {
			// 过滤记录日期
			filterByDate(record) {
				const currentDate = new Date();
				const recordDate = new Date(record.createTime);
				const filter = this.timeFilters.find(f => f.active);
				const filterDays = filter ? filter.days : 0;

				if (filterDays === 0) {
					// 今天
					return recordDate.toDateString() === currentDate.toDateString();
				} else if (filterDays === 7) {
					// 近7天
					const sevenDaysAgo = new Date();
					sevenDaysAgo.setDate(currentDate.getDate() - 7);
					return recordDate >= sevenDaysAgo;
				} else if (filterDays === 30) {
					// 近30天
					const thirtyDaysAgo = new Date();
					thirtyDaysAgo.setDate(currentDate.getDate() - 30);
					return recordDate >= thirtyDaysAgo;
				} else {
					// 自定义日期范围（如有选择日期）
					if (this.filterParams.startTime && this.filterParams.endTime) {
						const startDate = new Date(this.filterParams.startTime);
						const endDate = new Date(this.filterParams.endTime);
						return recordDate >= startDate && recordDate <= endDate;
					}
				}

				return true;
			},

			// 切换导航
			changeTab(e) {
				this.currentTab = e
				if (e === 1 && this.records.length === 0) {
					this.loadRecords()
				}
			},

			// 时间筛选
			changeTimeFilter(index) {
				this.timeFilters.forEach((item, i) => {
					item.active = i === index
					if (i === index && item.days === -1) {
						this.showCalendar = true
					}
				})
				this.loadRecords()
			},

			// 日期选择
			changeDate(e) {
				this.filterParams.startTime = e.startDate
				this.filterParams.endTime = e.endDate
				this.loadRecords()
			},

			// 加载记录
			async loadRecords() {
				if (this.loading) return
				this.loading = true

				try {
					const {
						data
					} = await this.util.request({
						url: '/api/record/list',//接口地址
						method: 'POST',
						data: this.filterParams
					})

					if (this.filterParams.page === 1) {
						this.records = data.list
					} else {
						this.records = [...this.records, ...data.list]
					}

					this.noMore = data.list.length < this.filterParams.size
					this.filterParams.page++
				} catch (e) {
					console.error("接口请求失败", e)
					uni.showToast({
						title: '加载录单记录失败，请稍后再试',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

			// 手动录单功能
			copyTemplate() {
				uni.setClipboardData({
					data: this.editableTemplate,
					success: () => {
						uni.showToast({
							title: '模板已复制'
						})
					}
				})
			},

			parseTemplate() {
				const pattern = /(\d+)\s*([\u4e00-\u9fa5]+)\s+(\d{11})\s+([\u4e00-\u9fa5]+)\s+([\u4e00-\u9fa5]+)/
				const match = this.editableTemplate.match(pattern)

				if (match) {
					this.formData = {
						serial: match[1].trim(),
						name: match[2].trim(),
						phone: match[3].trim(),
						address: match[4].trim(),
						remark: match[5].trim()
					}
				} else {
					uni.showToast({
						title: '模板格式错误，请参考示例格式',
						icon: 'none',
						duration: 2000
					})
				}
			},

			async submitForm() {
				if (!this.validateForm()) return

				try {
					await this.util.request({
						url: '/api/record/create',
						method: 'POST',
						data: this.formData
					})

					uni.showToast({
						title: '提交成功',
						icon: 'success'
					})
					this.resetForm()
				} catch (e) {
					console.error(e)
				}
			},

			validateForm() {
				const {
					serial,
					phone
				} = this.formData
				if (!serial) {
					uni.showToast({
						title: '请输入流水号',
						icon: 'none'
					})
					return false
				}
				if (!/^1[3-9]\d{9}$/.test(phone)) {
					uni.showToast({
						title: '手机号格式错误',
						icon: 'none'
					})
					return false
				}
				return true
			},

			resetForm() {
				this.formData = {
					serial: '',
					phone: '',
					name: '',
					address: '',
					remark: ''
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.manual-entry {
		background: #f5f5f5;
		min-height: 100vh;

		/* 顶部导航样式 */
		.tabsStyl {
			flex: 1;
			min-width: 0rpx;
			margin: 0 auto;
			background: #FFF;
		}

		/* 公共内容区样式 */
		.content-section,
		.record-section {
			padding: 20rpx;
			background: #fff;
		}

		/* 手动录单样式 */
		.template-editor {
			margin: 20rpx;
			background: #f8f8f8;
			border-radius: 8rpx;

			::v-deep .u-input {
				padding: 20rpx;
				font-size: 28rpx;
				min-height: 200rpx;
			}
		}

		.action-btns {
			display: flex;
			gap: 20rpx;
			padding: 0 20rpx;
			margin-bottom: 30rpx;

			button {
				flex: 1;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 8rpx;
				font-size: 28rpx;

				&.copy-btn {
					background: #f0f0f0;
					color: #666;
				}

				&.paste-btn {
					background:  #FE9367;
					color: #fff;
				}
			}
		}

		.entry-form {
			.form-item {
				display: flex;
				align-items: center;
				padding: 25rpx 0;
				border-bottom: 1rpx solid #eee;

				.label {
					width: 140rpx;
					font-size: 28rpx;
					color: #666;
				}

				::v-deep .u-input {
					flex: 1;
					font-size: 28rpx;
					padding: 0 20rpx;
				}
			}
		}

		.submit-btn {
			margin: 40rpx 20rpx;
			height: 88rpx;
			line-height: 88rpx;
			background:  #FE9367;
			color: #fff;
			border-radius: 8rpx;
			font-size: 32rpx;
		}

		/* 录单记录样式 */
		.filter-bar {
			background: #fff;
			// padding: 20rpx 0;
		}

		.record-list {
			.record-item {
				display: flex;
				flex-direction: column;
				justify-content: flex-start;
				align-items: flex-start;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #eee;

				.record-field {
					display: flex;
					align-items: center;
					padding: 12rpx 0;
					width: 100%;
					
					/* 黄色竖线 */
					.line {
						width: 4px;
						height: 20px;
						background-color:  #FE9367;
						margin-right: 10rpx;
						border-radius: 10rpx;
					}

					.label {
						width: 120rpx;
						color: #666;
						font-size: 28rpx;
					}

					.value {
						flex: 1;
						font-size: 28rpx;
						color: #333;
					}
				}
			}
		}
	}
</style>
